# leetcode 110 判断平衡二叉树

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        # 后序遍历求高度
        def get_height(node): #求子树的高度
            if node is None:
                return 0
            left_height = get_height(node.left)  # 左子树的高度
            right_height = get_height(node.right) # 右子树的高度
            if abs(left_height - right_height) > 1:
                return -1
            if left_height == -1 or right_height == -1:
                return -1
            return 1 + max(left_height, right_height)
        result = get_height(root)
        if result == -1:
            return False
        return True
